package ch.bfh.mobicomp.soda2.magnetometer.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;

import ch.bfh.mobicomp.soda2.magnetometer.MainActivity;
import ch.bfh.mobicomp.soda2.magnetometer.interfaces.IFileNameKnowing;
import android.annotation.SuppressLint;
import android.os.Environment;
import android.util.Log;

@SuppressLint("WorldReadableFiles")
public class FileWriting {
	
	private OutputStreamWriter outputStreamWriter;
	private File file;
	private String currentFileName;
	private IFileNameKnowing fileNameKnowing;
	
	public FileWriting(IFileNameKnowing fileNameKnowing) {
		
		this.fileNameKnowing = fileNameKnowing;
		if(!isWritable()) {
			Log.d(MainActivity.LOG_TAG, "no access to file");
			throw new RuntimeException("no access to File");
		}
		
		this.currentFileName = "magnetometer" + System.currentTimeMillis() + ".log";
		file = new File(Environment.getExternalStorageDirectory(), this.currentFileName);
		
		this.fileNameKnowing.onFileNameChanged(this.currentFileName);
		
		if(!file.exists()) {
			try {
				file.createNewFile();
			} catch (IOException e) {
				throw new RuntimeException("not created");
			}
		}
	}

	public boolean isWritable() {

		String state = Environment.getExternalStorageState();
		
		if (Environment.MEDIA_MOUNTED.equals(state)) {
		    // We can read and write the media
			return true;
			
		} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
		    return false;
		} else {
			// Something else is wrong. It may be one of many other states, but all we need
		    //  to know is we can neither read nor write
		    return false;
		}
	}

	public void fileLog(String stringToLog) {
	    try {
	    	outputStreamWriter = new OutputStreamWriter(new FileOutputStream(file, true));
            outputStreamWriter.append(stringToLog);
            outputStreamWriter.flush();
            outputStreamWriter.close();
        }
        catch (IOException e) {
            Log.e(MainActivity.LOG_TAG, "File write failed: " + e.toString());
        }
	}
	
	public String getCurrentFileName() {
		return currentFileName;
	}
}
